package com.example.question.list.list1;

/**
 * @Date 2023-07-04
 * @Author Jonathan
 * @link {<a href="https://leetcode.cn/problems/remove-nth-node-from-end-of-list/">...</a>}
 */
public class Code07_19 {
    Integer index = 0;

    public static void main(String[] args) {
        ListNode list2 = List.createList(new int[]{1, 2, 3, 4, 5, 6});
        Code07_19 code = new Code07_19();
        ListNode node = code.removeNthFromEnd(list2, 6);
        List.printLink(node);
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1, head);
        process(dummy, n);
        return dummy.next;
    }

    /**
     * 要在倒数第(n+1)个时候 去掉倒数第n个 经典递归算法
     *
     * @param head
     * @param n
     */
    private void process(ListNode head, int n) {
        if (head == null) {
            index = 0;
            return;
        }
        process(head.next, n);
        ++index;
        // 要在倒数第(n+1)个时候 去掉倒数第n个
        if (index == n + 1) {
            ListNode delNode = head.next;
            head.next = head.next.next;
            delNode.next = null;
        }
    }

    // todo 还可以用迭代的方法  或者  双指针的方法
}
